package com.omesoft.hksnore.util.omeview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.omesoft.hksnore.util.L;
import com.omesoft.hksnore.util.photo.MyPixelConvertUtil;

import java.util.List;
import java.util.Random;

/**
 * 录音绘图
 *
 * @autor omesoft_lgc
 * <p/>
 * create at 2017/5/17 20:58
 */
@SuppressLint("DrawAllocation")
public class RecordPragram extends View {

    private Paint paint;
    private Paint paint1;
    private Paint paint2;
    private Paint paint3;
    private Paint paint4;
    private Random random;// 随机数，用于随机生成条柱的高度
    private int width_Block = 10;// 用于控制小模块以及条柱的宽度
    private int height_Block = 10;// 小方块的高度
    private boolean canDraw = false;// 控制是否绘图
    private int width_Canvas, height_Canvas;

    private int length = 2048;//
    private int columnCount = length;// 整个画布中，条柱的条数
    private int point_X[] = new int[length];
    private int point_Y[] = new int[length];
    private int point_x[] = new int[length];
    private int point_y[] = new int[length];
    private Rect rect_Block[] = new Rect[length];// 小方块矩形框
    private Rect rect_Column[] = new Rect[length];// 条柱矩形框

    int eatchWidth = 30;//每个点的宽度
    float max = 128.0f;//最大值
    int avgMax = 0;
    Point tempAvg;


    private static final int maxColums = 128;
    private int up;// 整体上移预留座标点位置


    private int[] lastY;
    private long lastTimeMillis;


    int[] outInt;
    int snore = 0;
    int stopCount = 0;
    /**
     * 显示的个数
     */
    int showCount = 8;
    int multiple = 3;//倍数
    float txLine = 1.4f;//线粗细
    /**
     * 曲线上总点数
     */
    private Point[] mPoints;
    private Context context;


    public RecordPragram(Context context) {
        super(context);
        this.context = context;
        initPaint(context);
    }

    public RecordPragram(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        initPaint(context);
    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        height_Canvas = getMeasuredHeight();
        width_Canvas = getMeasuredWidth();
    }

    public void init(int _length) {
        this.length = _length;
        columnCount = length;// 整个画布中，条柱的条数
        eatchWidth = width_Canvas / showCount;
        point_X = new int[length];
        point_Y = new int[length];
        point_x = new int[length];
        point_y = new int[length];
        rect_Block = new Rect[length];// 小方块矩形框
        rect_Column = new Rect[length];// 条柱矩形框

        avgMax = height_Canvas;
        tempAvg = new Point(avgMax, avgMax);

        lastY = new int[maxColums];


        for (int i = 0; i < maxColums; i++) {
            lastY[i] = avgMax;
        }
        lastTimeMillis = System.currentTimeMillis();
    }

    /**
     * 计算最大值
     *
     * @param arr
     * @return
     */
    public static int getMax(int[] arr) {
        int max = arr[0];

        for (int x = 1; x < arr.length; x++) {
            if (arr[x] > max)
                max = arr[x];

        }
        return max;

    }

    /**
     * 计算最大值
     *
     * @param arr
     * @return
     */
    public static int getMax(List<Integer> arr) {
        int max = arr.get(0);

        for (int x = 1; x < arr.size(); x++) {
            if (arr.get(x) > max)
                max = arr.get(x);

        }
        return max;

    }

    /**
     * 设置每个点的位置
     *
     * @param outInt
     * @return
     */
    private Point[] getPoints(int[] outInt) {
        int length = outInt.length;
        Point[] points = new Point[length];

        long t = System.currentTimeMillis();
        int speed = (int) (t - lastTimeMillis) / 10; // 峰值下落速度
        lastTimeMillis = t;
        int j = 0;
        for (int i = 4; i < length; i++) {
            int x = 0;
            if (i == 4) {
                x = 0;
            } else {
                x = eatchWidth * j;
            }
            int value = outInt[j] * multiple;
            if (value > max) {
                value = (int) max;
            }
            int rh = height_Canvas - (int) ((float) (value / max) * height_Canvas);

            lastY[j] += speed << 1;

            /******************************/
            if (rh > lastY[j]) {
                rh = lastY[j];
            }
            lastY[j] = rh;


            points[j] = new Point(x, rh);

            j++;
        }
        return points;
    }

    /**
     * 设置画线
     *
     * @param canDraw
     * @param outInt
     * @param _snore
     */
    public void update2(boolean canDraw, int[] outInt, int _snore, int _snore2) {
        synchronized (outInt) {
            if (outInt.length == 0) {
                return;
            }
            this.snore = _snore;
            this.stopCount = _snore2;
            try {
                columnCount = outInt.length;
                this.canDraw = canDraw;
                this.outInt = outInt;
                mPoints = new Point[columnCount];
                synchronized (mPoints) {
                    mPoints = getPoints(outInt);
                    handler.sendEmptyMessage(0);
                }


            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (canDraw) {
            canvas.translate(0, -50);
            drawLine(canvas);
        } else {
            Paint p = new Paint();
            //清屏
            p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
            p.setColor(Color.TRANSPARENT);
            canvas.drawRect(0,height_Canvas,width_Canvas,height_Canvas,p);


        }
    }

    /**
     * 画曲线
     */
    public void drawLine(Canvas canvas) {
        Point startp = new Point();
        Point endp = new Point();

        paint.setStyle(Style.STROKE);
        Path path = new Path();
        Path path1 = new Path();
        Path path2 = new Path();
        Path path3 = new Path();
        Path path4 = new Path();

        L.e("xx", "画曲线length " + mPoints.length);
        for (int i = 0; i < showCount; i++) {
            if (mPoints[i] != null) {
                startp = mPoints[i];
                endp = mPoints[i + 1];
                int wt = (startp.x + endp.x) / 2;
                Point p3 = new Point();
                Point p4 = new Point();
                p3.y = startp.y;
                p3.x = wt;
                p4.y = endp.y;
                p4.x = wt;

                int scal =0;
                if (i == 0) {//处理开始点
                    scal = startp.y - height_Canvas;
                    path.moveTo(startp.x, startp.y);
                    if (height_Canvas == startp.y) {

                        path1.moveTo(startp.x, startp.y);
                        path2.moveTo(startp.x, startp.y);
                        path3.moveTo(startp.x, startp.y);
                        path4.moveTo(startp.x, startp.y);
                    }else{

                        path1.moveTo(startp.x, startp.y- (scal * 0.3f));
                        path2.moveTo(startp.x, startp.y- (scal * 0.5f));
                        path3.moveTo(startp.x, startp.y- (scal * 0.7f));
                        path4.moveTo(startp.x, startp.y- (scal * 0.8f));
                    }
                } else {//处理结束点
                    scal = endp.y - height_Canvas;
                    if (height_Canvas == endp.y) {
                        path.cubicTo(p3.x, p3.y, p4.x, p4.y, endp.x, endp.y);
                        path1.cubicTo(p3.x, p3.y, p4.x, p4.y, endp.x, endp.y);
                        path2.cubicTo(p3.x, p3.y, p4.x, p4.y, endp.x, endp.y);
                        path3.cubicTo(p3.x, p3.y, p4.x, p4.y, endp.x, endp.y);
                        path4.cubicTo(p3.x, p3.y, p4.x, p4.y, endp.x, endp.y);
                    } else {
                        path.cubicTo(p3.x, p3.y, p4.x, p4.y, endp.x, endp.y);
                        path1.cubicTo(p3.x, p3.y - (scal * 0.3f), p4.x, p4.y - (scal * 0.3f), endp.x, endp.y - (scal * 0.3f));
                        path2.cubicTo(p3.x, p3.y - (scal * 0.5f), p4.x, p4.y - (scal * 0.5f), endp.x, endp.y - (scal * 0.5f));
                        path3.cubicTo(p3.x, p3.y - (scal * 0.7f), p4.x, p4.y - (scal * 0.7f), endp.x, endp.y - (scal * 0.7f));
                        path4.cubicTo(p3.x, p3.y - (scal * 0.85f), p4.x, p4.y - (scal * 0.85f), endp.x, endp.y - (scal * 0.85f));
                    }
                }

                canvas.drawPath(path4, paint4);
                canvas.drawPath(path3, paint3);
                canvas.drawPath(path2, paint2);
                canvas.drawPath(path1, paint1);
                canvas.drawPath(path, paint);
            }

        }

    }

    /**
     * 设置画柱状
     *
     * @param canDraw
     * @param outInt
     * @param _snore
     */
    public void update(boolean canDraw, int[] outInt, int _snore, int _snore2) {
        synchronized (outInt) {
            if (outInt.length == 0) {
                return;
            }
            this.snore = _snore;
            this.stopCount = _snore2;
            try {
                columnCount = outInt.length;
                this.canDraw = canDraw;
                this.outInt = outInt;
                String str = "";
                String str2 = "";
                Log.e("xx", "----------outInt.length-------- " + outInt.length);

                int max1 = getMax(outInt);

                int startX = 0;
                int startY = 0;
                int stopX = 0;
                int stopY = 0;

                Log.e("xx", outInt.length + "----------开始添加数据------- " + columnCount);
                for (int i = 0; i < columnCount; i++) {
                    point_X[i] = eatchWidth * (i + 1);

                    int rh = (int) ((float) (outInt[i] / max) * height_Canvas);
                    str2 += outInt[i] + ",";

                    startX = point_X[i];
                    startY = height_Canvas - rh;

                    stopX = point_X[i] + width_Block * 2;
                    stopY = height_Canvas;

                    point_Y[i] = startY;

                    rect_Column[i] = new Rect(startX, startY, stopX, stopY);

                    str += startY + ",";


                }
                handler.sendEmptyMessage(0);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }


    /**
     * 清除画布
     */
    public void clear() {
        handler.sendEmptyMessage(2);
    }


    /**
     * 画条状
     *
     * @param canvas
     */
    private void drawBar(Canvas canvas) {
        for (int i = 0; i < columnCount; i++) {
            canvas.drawRect(rect_Column[i], paint);// 绘制条柱
//				canvas.drawRect(rect_Block[i], paint);// 绘制小方块
        }
    }

    Handler handler = new Handler() {
        public void dispatchMessage(android.os.Message msg) {

            switch (msg.what) {
                case 0:
                    invalidate();
                    break;
                case 2:
                    canDraw = false;
                    invalidate();
                    break;
            }

        }

        ;
    };


    /*
     * 初始化所有小方块的宽、高信息
     */
    private void intiRectBlock() {
        for (int i = 0; i < columnCount; i++) {
            point_x[i] = point_X[i];
            // 判断条柱上次高度与当前本次高度的高度值如若本次高度未达到上次高度则小方块的高度逐渐，实现下落的效果
            if (point_y[i] > point_Y[i] - height_Block) {
                point_y[i] = point_y[i] - 10;
            } else {
                point_y[i] = point_Y[i];
            }
            rect_Block[i] = new Rect(point_x[i] - width_Block / 2, height_Canvas - point_y[i], point_x[i] + width_Block / 2, height_Canvas - point_y[i] + 10);
        }
    }

    /*
     * 初始化画笔Paint
     */
    private void initPaint(Context context) {
        paint = new Paint();
        paint.setDither(true);// 去抖动
        paint.setAntiAlias(true);// 抗锯齿
        paint.setStyle(Style.FILL);// 设置填充模式
        paint.setColor(Color.parseColor("#A89968"));
        paint.setTextSize(50);
        paint.setStrokeWidth(MyPixelConvertUtil.dip2px(context, 1f));


        paint1 = new Paint();
        paint1.setDither(true);// 去抖动
        paint1.setAntiAlias(true);// 抗锯齿
        paint1.setStyle(Style.FILL);// 设置填充模式
        paint1.setColor(Color.parseColor("#7E7459"));
        paint1.setTextSize(50);
        paint1.setStrokeWidth(MyPixelConvertUtil.dip2px(context, txLine));

        paint2 = new Paint();
        paint2.setDither(true);// 去抖动
        paint2.setAntiAlias(true);// 抗锯齿
        paint2.setStyle(Style.FILL);// 设置填充模式
        paint2.setColor(Color.parseColor("#696251"));
        paint2.setTextSize(50);
        paint2.setStrokeWidth(MyPixelConvertUtil.dip2px(context, txLine));

        paint3 = new Paint();
        paint3.setDither(true);// 去抖动
        paint3.setAntiAlias(true);// 抗锯齿
        paint3.setStyle(Style.FILL);// 设置填充模式
        paint3.setColor(Color.parseColor("#56524A"));
        paint3.setTextSize(50);
        paint3.setStrokeWidth(MyPixelConvertUtil.dip2px(context, txLine));


        paint4 = new Paint();
        paint4.setDither(true);// 去抖动
        paint4.setAntiAlias(true);// 抗锯齿
        paint4.setStyle(Style.FILL);// 设置填充模式
        paint4.setColor(Color.parseColor("#4C4946"));
        paint4.setTextSize(50);
        paint4.setStrokeWidth(MyPixelConvertUtil.dip2px(context, txLine));

        paint1.setStyle(Style.STROKE);
        paint2.setStyle(Style.STROKE);
        paint3.setStyle(Style.STROKE);
        paint4.setStyle(Style.STROKE);
    }

    public boolean isCanDraw() {
        return canDraw;
    }

    public void setCanDraw(boolean canDraw) {
        this.canDraw = canDraw;
    }

}

